import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { tdtMapKey, BaseRegionCode, BaseGeoServerType, BaseRegionName, BaseAppCode, mapMaxLevel } from '/@/config/geoserver';
import {
	getGeoJsonFromGeoserver,
	ynLandImage,
	gbnLandImage,
	uavOpenImage,
} from '/@/api/geoserver/map';
import { getUavImageLayerList } from '../api/uav-open';

export default {
	data() {
		return {
			/**
			 * @type {L.Map}
			 */
			map: null,
			mapCenter: [29.154282, 119.793462], //地图中心
			mapZoom: 10, //地图层级
			regionLinesLayer: null, // 区域边界信息
			widthRegionLayer: null, //外层边界
			regionNameMarkers: [], // 存放区域显示名称
			timer: null, //超时时间区分单击和双击
			baseMapLayerGroup: null, //底图图层
			layerTypeList: ['无人机影像', '卫星影像'],
			uavLayerType: '卫星影像',
			uavLayer: null, //无人机影像图层组
			uavLayerCodes: [], //影像code集合
			singleUavLayerGroup: null, // 单份成果影像及边界
			uavTimes: [], //无人机影像时间列表
			uavTime: '', //无人机影像时间
			uavDayTimes: [], //无人机影像日期列表，存放日期 select placeholder 默认 不限日期
			uavDay: '', //无人机影像日期
			isShowUavTime: false, //是否显示无人机时间
			regionCode: '', // 当前区域编码,初始值根据默认区域变化
			regionName: '', //当前区域名称
			regionInfoList: [], //存放区域，用于下钻和返回
			isClickRegion: false, // 是否点击了区域,防止重复点击
			isClickMap: false, //是否点击地图，获取地图定位点数据，用于加载当前地块信息
			latitude: 0, //地图点击点坐标
			longitude: 0, //地图点击点坐标
			acre_id: '', //点击点对应的图斑id
			geoserver_acre_info: '', //点击点对应的图斑数据
			layerGroups: null, //图层组get，存放所有图层，图层设置不同的层级
			gnqLayer: null, //粮食功能区图层
			gbnLayer: null, //高标农图层
			ynLayer: null, //永农图层
			regionLayer: null, //
			clickRegionCode: '', //获取点击的区域code
			clickRegionName: '', //获取点击的区域name
			isShowSatelliteImage: true, //是否显示卫星影像，默认显示
			isDoubleClick: false, //是否双击
			isLoadOver: false, //地图是否加载完成
			loadingUav: false, // 点击预览-加载无人机影像
			isShowRegionLayer: true, //是否显示区域边界
			defaultSetView: true, //是否默认移动地图中心点
			isShowMapBg: true, //是否显示地图背景
			uavDataKey: "", //无人机影像云--加载影像key
			uavDayObj: {}, //无人机影像云--日期数组，存放所有日期
		};
	},
	methods: {
		/**
		 * 初始化地图
		 * @param {*} mapId
		 */
		initMap(mapId: string) {
			let that = this;
			that.map = L.map(mapId, {
				crs: L.CRS.EPSG4326,
				center: that.mapCenter,
				maxZoom: mapMaxLevel,
				minZoom: 5,
				zoom: that.mapZoom,
				zoomControl: false,
				attributionControl: false,
				preferCanvas: true,
				doubleClickZoom: false,
				...(this.defaultMapOption ? this.defaultMapOption : {}),
			});
			//添加窗格，把wms图层添加到此窗格中，可以在geojson图层上展示
			that.isLoadOver = true;
			that.map.createPane('maxLevelPane');
			that.map.getPane('maxLevelPane').style.zIndex = 590;
			that.map.on('dblclick', function (e) {
				//禁用地图点击事件
				if (that.isDisableMapClick) {
					return;
				}
				if (!that.isShowRegionLayer) {
					return;
				}
				if (that.timer) {
					window.clearTimeout(that.timer);
					that.timer = null;
				}
				//判断是否已经点击区域，防止重复触发
				if (that.isClickRegion) {
					that.isClickRegion = false;
					return;
				}
				if (that.isClickMap) {
					//点击地图，抛出事件
					that.latitude = e.latlng.lat;
					that.longitude = e.latlng.lng;
					return;
				}
				if (that.regionCode == BaseRegionCode.value) {
					return;
				}
				//层级发生变化，清理之前的区域边界和区域名称
				if (that.regionLinesLayer) {
					that.regionLinesLayer.clearLayers();
				}
				if (that.regionNameMarkers.length > 0) {
					that.regionNameMarkers.forEach((item) => {
						item.clearLayers();
					});
					that.regionNameMarkers = [];
				}
				that.regionInfoList.pop();
				let lastRegion = that.regionInfoList[that.regionInfoList.length - 1];
				that.regionCode = lastRegion.regionCode;
				that.regionName = lastRegion.name;
				that.getRegionListWms(that.regionCode, that.map);
				that.getRegionListWmsForSingle(that.regionCode, that.map);
			});
			that.map.on('click', function (e) {
				console.log('lat = ' + e.latlng.lat + ';lng = ' + e.latlng.lng);
				//判断是否已经点击区域，防止重复触发
				if (that.isClickRegion) {
					that.isClickRegion = false;
					return;
				}
				that.timer = window.setTimeout(() => {
					if (that.isClickMap) {
						//点击地块图层，抛出事件
						that.latitude = e.latlng.lat;
						that.longitude = e.latlng.lng;
						return;
					}
				}, 300);
			});
			that.addSateLayer();
			if (that.isShowRegionLayer) {
				that.getRegionListWms(BaseRegionCode.value, that.map);
				that.getRegionListWmsForSingle(BaseRegionCode.value, that.map);
			}
		},
		/**
		 * 添加卫星影像
		 */
		addSateLayer() {
			if (!this.isShowMapBg) return;
			let layerType = this.isShowSatelliteImage ? 'img' : 'vec';
			let labelType = this.isShowSatelliteImage ? 'cia' : 'cva';
			if (!this.baseMapLayerGroup) {
				this.baseMapLayerGroup = new L.LayerGroup();
				this.baseMapLayerGroup.addTo(this.map);
			} else {
				this.baseMapLayerGroup.clearLayers();
			}
			var wMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${layerType}_c&x={x}&y={y}&l={z}&tk=${tdtMapKey}`, {
				minZoom: 5,
				maxZoom: mapMaxLevel,
				maxNativeZoom: 17,
				minNativeZoom: 5,
				subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
				zoomOffset: 1,
				tileSize: 256,
			});
			var lMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${labelType}_c&x={x}&y={y}&l={z}&tk=${tdtMapKey}`, {
				subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
				transparent: true,
				zIndex: 3,
				zoomOffset: 1,
				minZoom: 5,
				maxZoom: mapMaxLevel,
				tileSize: 256,
			});
			this.baseMapLayerGroup.addLayer(wMap);
			this.baseMapLayerGroup.addLayer(lMap);
		},
		//#region 各区域边界
		/**
		 * 加载单一区域边界
		 * @param {*} data
		 * @param {*} toMap
		 */
		async getRegionListWmsForSingle(code_region, toMap) {
			if (this.widthRegionLayer) {
				this.map.removeLayer(this.widthRegionLayer);
			}
			var regionStyle = {
				color: '#89cfda',
				weight: 5,
				opacity: 1,
				fillColor: '',
				fillOpacity: 0,
			};
			var param = {
				service: 'WFS',
				version: '1.0.0',
				request: 'GetFeature',
				typeName: `${BaseGeoServerType.value}:AR-REGION`,
				maxFeatures: 10000,
				outputFormat: 'application/json',
				CQL_FILTER: `region_code = '${code_region}'`,
			};
			let data = await getGeoJsonFromGeoserver(param, `${BaseGeoServerType.value}:AR-REGION`);
			var geo_l = L.geoJson(data, {
				style: regionStyle,
			}).addTo(toMap);
			geo_l.bringToBack(); //放到底层
			this.widthRegionLayer = geo_l;
			var zoom = 10;
			if (code_region.length == 9) {
				zoom = 12;
			} else if (code_region.length == 12) {
				zoom = 13;
			}
			var center = [data.features[0].properties.latitude, data.features[0].properties.longitude];
			this.defaultSetView && toMap.setView(center, zoom);
		},
		/**
		 * 加载geoserver区域边界
		 * region_code = '${code_region}
		 */
		getRegionListWms(code_region, toMap) {
			if (!this.regionLinesLayer) {
				this.regionLinesLayer = new L.LayerGroup();
				this.regionLinesLayer.addTo(toMap);
			}
			var regionStyle = {
				color: '#89cfda',
				weight: 1,
				opacity: 1,
				fillColor: '#2c5ba9',
				fillOpacity: this.isShowSatelliteImage ? 0 : 1,
			};
			let that = this;
			var param = {
				service: 'WFS',
				version: '1.0.0',
				request: 'GetFeature',
				typeName: `${BaseGeoServerType.value}:AR-REGION`,
				maxFeatures: 10000,
				outputFormat: 'application/json',
				CQL_FILTER: `parent_code = '${code_region}'`,
			};
			getGeoJsonFromGeoserver(param, `${BaseGeoServerType.value}:AR-REGION`).then((res) => {
				var data = res;
				if (data.features.length > 0) {
					var markerArray = [];
					var geo_l = L.geoJson(data, {
						onEachFeature: function (feature, layer) {
							if (feature.geometry.type === 'MultiPolygon' || feature.geometry.type === 'Polygon') {
								layer.setStyle(regionStyle);
								var center = {
									lat: feature.properties.latitude,
									lng: feature.properties.longitude,
								};
								var content = `<div style='color:#ffffff;width:32px;margin-left: -16px;font-size:12px;'>${feature.properties.name}</div>`;
								var icon_div = L.divIcon({
									html: content,
									className: 'town_name',
								});
								let marker = L.marker(center, {
									icon: icon_div,
									clickable: false,
									draggable: false,
								});
								markerArray.push(marker);
							}
						},
					}).addTo(toMap);
					that.regionLinesLayer.addLayer(geo_l);
					let markerGroup = L.layerGroup(markerArray);
					toMap.addLayer(markerGroup);
					that.regionNameMarkers.push(markerGroup);
					geo_l.on('dblclick', function (e) {
						//禁用地图点击事件
						if (that.isDisableMapClick) {
							return;
						}
						that.isDoubleClick = true;
						if (that.timer) {
							window.clearTimeout(that.timer);
							that.timer = null;
						}
						//判断是否是点击地图获取经纬度
						if (that.isClickMap) {
							return;
						}
						//防止地图重复触发双击事件
						that.isClickRegion = true;
						var code = e.sourceTarget.feature.properties.region_code;
						var name = e.sourceTarget.feature.properties.name;
						//到村结束
						if (code.length == 12) {
							return;
						}
						that.regionCode = code;
						that.regionName = name;
						that.regionInfoList.push({
							name: name,
							regionCode: code,
						});
						if (that.regionLinesLayer) {
							that.regionLinesLayer.clearLayers();
						}
						if (that.regionNameMarkers.length > 0) {
							that.regionNameMarkers.forEach((item) => {
								item.clearLayers();
							});
							that.regionNameMarkers = [];
						}
						that.getRegionListWms(code, that.map);
						that.getRegionListWmsForSingle(code, that.map);
					});
					geo_l.on('click', function (e) {
						//判断是否是点击地图获取经纬度
						if (that.isClickMap) {
							return;
						}
						that.isClickRegion = true;
						that.timer = window.setTimeout(() => {
							if (that.isDoubleClick) {
								that.isDoubleClick = false;
								return;
							}
							var prop = e.sourceTarget.feature.properties;
							if (prop.grade != '3' && prop.grade != '4') return;
							that.clickRegionCode = prop.region_code;
							that.clickRegionName = prop.name;
						}, 300);
					});
					geo_l.on('mouseover', function (e) {
						var layer = e.sourceTarget;
						layer.setStyle({
							weight: 3,
							fillColor: '#2d6fb7',
							fillOpacity: that.isShowSatelliteImage ? 0 : 1,
						});
					});
					geo_l.on('mouseout', function (e) {
						var layer = e.sourceTarget;
						layer.setStyle({
							weight: 1,
							fillColor: '#2c5ba9',
							fillOpacity: that.isShowSatelliteImage ? 0 : 1,
						});
					});
				}
			});
		},

		/**
		 * 点击区域名称返回对应层级
		 * @param {*} item
		 * @param {*} index
		 */
		handleBackUpForMap(item, index) {
			if (this.regionInfoList.length == 1 || index == this.regionInfoList.length - 1) {
				return;
			}
			var array = this.regionInfoList.slice(0, index + 1);
			this.regionInfoList = array;
			this.doubleClickMap(item);
		},
		doubleClickMap(regionInfo) {
			let that = this;
			//判断是否是默认最高区域
			//层级发生变化，清理之前的区域边界和区域名称
			//层级发生变化，清理之前的区域边界和区域名称
			if (that.regionLinesLayer) {
				that.regionLinesLayer.clearLayers();
			}
			if (that.regionNameMarkers.length > 0) {
				that.regionNameMarkers.forEach((item) => {
					item.clearLayers();
				});
				that.regionNameMarkers = [];
			}
			if (regionInfo) {
				that.regionCode = regionInfo.regionCode;
				that.regionName = regionInfo.name;
				that.getRegionListWms(that.regionCode, that.map);
				that.getRegionListWmsForSingle(that.regionCode, that.map);
			}
		},

		//#endregion
		//#region  无人机相关接口
		/**
   * 无人机时间切换
   */
		handleUavTimeChange(e) {
			if (this.uavLayer) {
				this.uavLayer.clearLayers();
			}
			this.getUavDayList();
			this.init_open_uav();
		},
		/**
		 * 无人机日期切换
		 * @param {*} e
		 */
		handleUavDayChange(e) {
			if (this.uavLayer) {
				this.uavLayer.clearLayers();
			}
			this.init_open_uav();
		},
		/**
   * 无人机和卫星影像切换
   * @param {*} e
   */
		handleUavLayerChange(e) {
			if (e == "卫星影像") {
				if (this.uavLayer) {
					this.uavLayer.clearLayers();
				}
				this.isShowUavTime = false;
				this.map.setMaxZoom(mapMaxLevel);
			} else {
				if (this.uavLayer) {
					this.uavLayer.clearLayers();
				}
				this.isShowUavTime = true;

				if (this.uavTime) {
					this.getUavDayList();
					this.init_open_uav();
				}
			}
		},
		/**
  * 无人机影像云 -- 获取时间列表
  * @param {*} regionCode
  * @param {*} tagIds
  * @param {*} needDay
  */
		async getUavTimeList(
			regionCode = BaseRegionCode.value,
			townName = "",
			tagIds = [],
			needDay = 1,
			useDelay
		) {
			return new Promise((resolve, reject) => {
				try {
					setTimeout(
						async () => {
							const { data } = await getUavTimeList({
								regionCode,
								townName,
								needDay,
								tagIds: tagIds.length > 0 ? tagIds.join(",") : "",
							});
							if (data.code == 0) {
								if (!data.data) {
									this.uavTimes = [];
									this.uavTime = "";
									this.uavDayObj = {};
									return;
								}
								this.uavDataKey = data.data.dataKey;
								let dateList = data.data.dataList;
								let list = [];
								let month_day_obj = {};
								dateList.forEach((item) => {
									month_day_obj = {
										...month_day_obj,
										...item.month,
									};
									let monthList = Object.keys(item.month);
									monthList.forEach((item_m) => {
										let time_str = `${item.year}-${item_m}`;
										if (list.findIndex((e) => e == time_str) == -1) {
											list.push(time_str);
										}
									});
								});
								this.uavTimes = this.formatterUavTimes
									? this.formatterUavTimes(list)
									: list;
								this.uavTime = list.length > 0 ? list[0] : "";
								this.uavDayObj = month_day_obj;
								resolve();
							}
						},
						useDelay ? 2000 : 0
					);
				} catch (e) {
					reject(e);
				}
			});
		},
		/**
		 * 无人机影像云 -- 获取日期列表
		 * @returns
		 */
		getUavDayList() {
			if (validatenull(this.uavTime)) return;
			this.uavDay = "";
			let temp_list = this.uavTime.split("-");
			let month = temp_list[1];
			this.uavDayTimes = this.formatterUavDayTimes
				? this.formatterUavDayTimes(this.uavDayObj[month])
				: this.uavDayObj[month];
		},
		/**
		 * 无人机影像云 -- 获取影像列表
		 * @returns
		 */
		async init_open_uav() {
			if (validatenull(this.uavTime)) return;
			let that = this;
			if (!this.uavLayer) {
				this.uavLayer = new L.LayerGroup();
				this.uavLayer.addTo(this.map);
			}
			let temp_list = this.uavTime.split("-");
			var param = {
				dataKey: this.uavDataKey,
				year: temp_list[0],
				month: temp_list[1],
			};
			if (this.uavDay) {
				param = Object.assign(param, {
					day: this.uavDay,
				});
			}
			const { data } = await getUavImageLayerList(param);
			if (data.code == 0) {
				let baseMapRegionCode = "";
				let wms = data.data.dataList.map((o) => {
					let temp_array = o.layerName.split(":");
					baseMapRegionCode = temp_array[0];
					return temp_array[1];
				});
				if (wms.length > 0) {
					if (wms.length > 5) {
						var array = [];
						wms.forEach((item, index) => {
							array.push(item);
							if (index == wms.length - 1) {
								let wmsLayer = uavOpenImage(array, baseMapRegionCode);
								wmsLayer.setZIndex(90);
								wmsLayer.options.maxZoom = mapMaxLevel;
								that.uavLayer.addLayer(wmsLayer);
								that.map.setMaxZoom(mapMaxLevel);
								array = [];
							} else {
								if (array.length >= 5) {
									let wmsLayer = uavOpenImage(array, baseMapRegionCode);
									wmsLayer.setZIndex(90);
									wmsLayer.options.maxZoom = mapMaxLevel;
									that.uavLayer.addLayer(wmsLayer);
									that.map.setMaxZoom(mapMaxLevel);
									array = [];
								}
							}
						});
					} else {
						let wmsLayer = uavOpenImage(wms, baseMapRegionCode);
						wmsLayer.setZIndex(90);
						wmsLayer.options.maxZoom = mapMaxLevel;
						that.uavLayer.addLayer(wmsLayer);
						that.map.setMaxZoom(mapMaxLevel);
					}
				}
			}
		},

		//#endregion
		//#region  获取点击点图斑信息相关接口
		/**
		 * 获取点击点地块信息
		 * @param {*} layerName  图层名称
		 * @param {*} lon
		 * @param {*} lat
		 */
		async getLandImgInfo(layerName = '', viewparams = '') {
			var param = {
				service: 'WFS',
				version: '1.0.0',
				request: 'GetFeature',
				typeName: `${BaseGeoServerType.value}:${layerName}`,
				maxFeatures: 10,
				outputFormat: 'application/json',
				CQL_FILTER: `CONTAINS(geom,SRID=4326;POINT(${this.longitude} ${this.latitude}))`,
				viewparams,
			};
			let data = await getGeoJsonFromGeoserver(param, `${BaseGeoServerType.value}:${layerName}`);
			this.loading = false;
			if (data.features.length > 0) {
				var item = data.features[0];
				this.geoserver_acre_info = item;
				//监听变化
			}
		},
		/**
		 * 加载永农图层
		 * @returns
		 */
		getYnWms() {
			if (!this.layerGroups) {
				this.layerGroups = new L.LayerGroup();
				this.layerGroups.addTo(this.map);
			}
			if (this.ynLayer) {
				this.layerGroups.addLayer(this.ynLayer);
				return;
			}
			var wmsLayer = ynLandImage();
			wmsLayer.setParams({
				styles: 'farmLandStyle',
			});
			wmsLayer.setZIndex(100);
			this.ynLayer = wmsLayer;
			this.layerGroups.addLayer(wmsLayer);
		},
		/**
		 * 移除永农图层
		 * @returns
		 */
		removeYnWms() {
			return this.ynLayer && this.layerGroups.removeLayer(this.ynLayer);
		},
		/**
		 * 加载高标农图层
		 * @returns
		 */
		getGbnWms() {
			if (!this.layerGroups) {
				this.layerGroups = new L.LayerGroup();
				this.layerGroups.addTo(this.map);
			}
			if (this.gbnLayer) {
				this.layerGroups.addLayer(this.gbnLayer);
				return;
			}
			var wmsLayer = gbnLandImage();
			wmsLayer.setParams({
				styles: 'blueStyle',
			});
			wmsLayer.setZIndex(110);
			this.gbnLayer = wmsLayer;
			this.layerGroups.addLayer(wmsLayer);
		},
		/**
		 * 移除高标农图层
		 * @returns
		 */
		removeGbnWms() {
			return this.gbnLayer && this.layerGroups.removeLayer(this.gbnLayer);
		},
	},

	async mounted() {
		await this.$nextTick();
		//无人机影像时间放到页面中加载
		this.getTimeList();
	},
	created() {
		this.regionCode = BaseRegionCode.value;
		this.regionName = BaseRegionName.value;
		this.regionInfoList.push({
			name: this.regionName,
			regionCode: this.regionCode,
		});
	},
	watch: {},
	beforeUnmount() {
		if (this.regionLinesLayer) {
			this.regionLinesLayer.clearLayers();
		}
		if (this.regionNameMarkers.length > 0) {
			this.regionNameMarkers.forEach((item) => {
				item.clearLayers();
			});
			this.regionNameMarkers = [];
		}
		if (this.layerGroups) {
			this.layerGroups.clearLayers();
			this.layerGroups = null;
		}
		if (this.uavLayer) {
			this.uavLayer.clearLayers();
			this.uavLayer = null;
		}
		if (this.ynLayer) {
			this.ynLayer = null;
		}
		if (this.gnqLayer) {
			this.gnqLayer = null;
		}
		if (this.gbnLayer) {
			this.gbnLayer = null;
		}

		if (this.map) {
			this.map.remove();
		}
	},
};
